package com.example.oracle.helper;



import java.lang.reflect.Field;
import java.util.List;

import com.example.oracle.utils.ReflectionUtils;
import com.github.pagehelper.PageHelper;

import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.FieldDefaults;

@Getter
@Setter
@FieldDefaults(level=AccessLevel.PRIVATE)
public class Page{


	Integer page;

	Object rows;

	String sort;

	String order;

	Long total;
	
	@SuppressWarnings("rawtypes")
	private void validateOrderField(boolean isPage, Class cls) {
		if (isPage) {
			PageHelper.startPage(page == null ? 1 : page, rows == null ? 10: Integer.valueOf(rows.toString()));
		}
		if (order != null && cls != null) {
            String[] orderFields = this.order.split(",");
            String[] sorts = this.sort.split(",");
            if (orderFields.length == sorts.length) {
                List<Field> fields = ReflectionUtils.getDeclaredField(cls);
                for (String sort : sorts) {
                    boolean isExsit = false;
                    for (Field field : fields) {
                        if (field.getName().equals(sort)) {
                            isExsit = true;
                            break;
                        }
                    }
                    if (!isExsit) {
                        throw new BusinessException("排序字段'{}'异常", sort);
                    }
                }
                StringBuilder orderBy = new StringBuilder();
                for (int i = 0; i < sorts.length; i++) {
                    if (i!=0) {
                        orderBy.append(",");
                    }
                    orderBy.append(sorts[i]).append(orderFields[i].equalsIgnoreCase("desc")?" desc":" asc");
                }
                PageHelper.orderBy(orderBy.toString());
            }
        }
	}
	
	public void initPagingData(Class<?> cls){
		this.validateOrderField(true, cls);
	}

	public void initAllData(Class<?> cls){
		this.validateOrderField(false, cls);
	}

	@SuppressWarnings("rawtypes")
	public Object getRows() {
		if (rows instanceof Integer) {
			return Integer.valueOf(rows.toString());
		}
		return (List) rows;
	}
	
	public Page setResult(List<?> result){
        com.github.pagehelper.Page<?> page = (com.github.pagehelper.Page<?>) result;
        this.total = page.getTotal();
        this.rows = page.getResult();
        return this;
    }

}
